import wtforms  # 导入表单相关模块
from wtforms.validators import Email, Length, EqualTo, InputRequired
from models import UserModel, EmailCaptchaModel
from exts import db


# 注册表单验证
class RegisterForm(wtforms.Form):
    # 邮箱验证：必须符合邮箱格式
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])
    # 验证码验证：必须是6位字符
    captcha = wtforms.StringField(validators=[Length(min=6, max=6, message="验证码格式错误！")])
    # 用户名验证：3-20个字符
    username = wtforms.StringField(validators=[Length(min=3, max=20, message="用户名格式错误！")])
    # 密码验证：6-20个字符
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误！")])
    # 确认密码验证：必须与password字段一致
    password_confirm = wtforms.StringField(validators=[EqualTo("password", message="两次密码不一样！")])

    # 自定义邮箱验证：检查邮箱是否已被注册
    def validata_email(self, field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        if user:  # 如果数据库中存在该邮箱,抛出错误
            raise wtforms.ValidationError(message="该邮箱已经被注册！")

    # 自定义验证码验证：检查验证码是否正确
    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        # 获取用户输入的邮箱、验证码，并从数据库查询匹配记录
        captcha_model = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
        if not captcha_model:  # 如果找不到匹配记录
            raise wtforms.ValidationError(message="邮箱或验证码错误！")


# 登录表单验证
class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误！")])


# 提问表单验证
class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[Length(min=3, max=100, message="标题格式错误！")])
    content = wtforms.StringField(validators=[Length(min=3, message="内容格式错误！")])


# 回答表单验证
class AnswerForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=3, message="内容格式错误！")])
    question_id = wtforms.IntegerField(validators=[InputRequired(message="需要传入问题id！")])
